package com.frank.leetcode.question_1_5;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/description/
 * 2. 两数相加
 * 难度: 中等
 * <p>
 * Question :
 * 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
 * 你可以假设除了数字 0 之外，这两个数字都不会以零开头。
 * <p>
 * Demo：
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 * <p>
 * <p>
 * Created by zhy on 2018/5/31.
 */
public class AddTwoNumbers {
    private static Logger LOG = LoggerFactory.getLogger(AddTwoNumbers.class);

    @Test
    public void run() {
        ListNode l1 = new ListNode(1);
        l1.add(8);
        ListNode l2 = new ListNode(0);

        ListNode answer = addTwoNumbers(l1, l2);
        System.out.println(answer.toString());
    }

    private ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = l1;
        ListNode l4 = l2;

        int flag = 0;
        int n = l1.val + l2.val;
        if (n >= 10) {
            n = n - 10;
            flag = 1;
        }
        ListNode l = new ListNode(n);
        ListNode now = l;

        while (l3.next != null || l4.next != null) {
            int val1 = 0;
            int val2 = 0;
            if (l3.next != null) {
                l3 = l3.next;
                val1 = l3.val;
            }
            if (l4.next != null) {
                l4 = l4.next;
                val2 = l4.val;
            }
            int val = val1 + val2 + flag;
            if (val >= 10) {
                val = val - 10;
                flag = 1;
            } else {
                flag = 0;
            }
            now.next = new ListNode(val);
            now = now.next;
        }
        if (flag > 0) {
            now.next = new ListNode(flag);
        }

        return l;
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        public ListNode add(int val) {
            next = new ListNode(val);
            return next;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(this.val).append(",");
            ListNode v = this;
            while ((v = v.next) != null) {
                sb.append(v.val).append(",");
            }
            return sb.toString();
        }
    }
}